package com.zhsource.system.controller;


import com.zhsource.auth.LoginDto;
import com.zhsource.exception.GlobalException;
import com.zhsource.system.service.ILoginService;
import com.zhsource.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录控制器
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILoginService loginService;

    /**
     * 账号密码登录
     * @return
     */
    @PostMapping("/account")
    public R<String> account(@RequestBody LoginDto loginDto){
        try {
            String token = loginService.account(loginDto);
            return R.ok("登录成功！", token);
        } catch (GlobalException e) {
            log.error("账号密码登录发生异常，异常信息为：{}", e.getMessage());
            return R.fail(401, "登录失败,失败原因为:"+ e.getMessage());
        } catch (AuthenticationException e) {
            log.error("账号密码登录发生异常，异常信息为：{}", e.getMessage());
            return R.fail(401,  e.getMessage());
        } catch (Exception e) {
            log.error("账号密码登录发生异常，异常信息为：{}", e.getMessage());
            return R.fail("系统异常，请重试！");
        }
    }

}
